/*           Copyright(c) 2005-2008 Dave Sexton            *
 *                   HtmlEditor Control                    *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace DaveSexton.Controls.Native
{
	/// <summary>
	/// Wraps an <c>OLECMD</c> structure and pins it in memory for use with COM-Interop calls.
	/// </summary>
	public sealed class OleCommand : IDisposable
	{
		#region Public Properties
		public IntPtr Handle
		{
			get
			{
				return handle.AddrOfPinnedObject();
			}
		}

		[CLSCompliant(false)]
		public uint Command
		{
			get
			{
				return info.cmdID;
			}
		}

		public OleCommandQueryTypes QueryTypes
		{
			get
			{
				return info.cmdf;
			}
		}
		#endregion

		#region Private / Protected
		private readonly GCHandle handle;
		private readonly OLECMD info;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="OleCommand" /> class.
		/// </summary>
		[CLSCompliant(false)]
		public OleCommand(uint command)
		{
			info = new OLECMD();
			info.cmdID = command;

			handle = GCHandle.Alloc(info, GCHandleType.Pinned);
		}
		#endregion

		#region IDisposable Members
		/// <summary>
		/// Releases all resources used by an instance of the <see cref="OleCommand" /> class.
		/// </summary>
		/// <remarks>
		/// This method calls the virtual <see cref="Dispose(bool)" /> method, passing in <strong>true</strong>, and then suppresses 
		/// finalization of the instance.
		/// </remarks>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// Releases unmanaged resources before an instance of the <see cref="OleCommand" /> class is reclaimed by garbage collection.
		/// </summary>
		/// <remarks>
		/// This method releases unmanaged resources by calling the virtual <see cref="Dispose(bool)" /> method, passing in <strong>false</strong>.
		/// </remarks>
		~OleCommand()
		{
			Dispose(false);
		}

		/// <summary>
		/// Releases the unmanaged resources used by an instance of the <see cref="OleCommand" /> class and optionally releases the managed resources.
		/// </summary>
		/// <param name="disposing"><strong>true</strong> to release both managed and unmanaged resources; <strong>false</strong> to release only unmanaged resources.</param>
		private void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (handle != null)
					handle.Free();
			}
		}
		#endregion

		#region Nested
		[StructLayout(LayoutKind.Sequential)]
		private sealed class OLECMD
		{
			public uint cmdID;
			public OleCommandQueryTypes cmdf;
		}
		#endregion
	}
}
